package com.zt.location.modules.upload.controller; 

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.zt.location.common.utils.R;
import com.zt.location.modules.sys.controller.AbstractController;

@RestController
@RequestMapping("/uploadfile")
public class UploadController extends AbstractController {

    private String filename;
    //Save the uploaded file to this folder
    private static String UPLOADED_FOLDER = "E:\\upload";

    /*
    **文件上传页面
     */

    @GetMapping("/upload")
    public String upload(){
        return "upload";
    }

    @PostMapping("/upload")
    public R singleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes) {

        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "文件为空! 请选择非空文件上传！");
            return R.ok();
        }

        try {
            // 获取文件并保存到指定文件夹中
            byte[] bytes = file.getBytes();
            filename = file.getOriginalFilename();
            Path path = Paths.get(UPLOADED_FOLDER +File.separator+ filename);
            Files.write(path, bytes);

            redirectAttributes.addFlashAttribute("message", "您已成功上传 '" + filename + "', 该文件大小约为 " +bytes.length/1024+" KB.");

        }
        catch (IOException e) {
            e.printStackTrace();
        }

        return R.ok();
    }

    /*
    ** 文件上传信息处理页面
     */
    @GetMapping("/uploadStatus")
    public String uploadStatus(){
        return "uploadStatus";
    }

    /*
    ** 数据预览页面： 支持CSV文件和部分图片格式的预览
     */

    @GetMapping("/review")
    public String review(Map<String, Object> map) {

        map.put("filename", filename);
        String filetype = filename.split("\\.")[1];
        map.put("filetype",filetype);
        System.out.println(filename);

        if(filetype.equals("csv")) {
            readCSV read_csv = new readCSV(UPLOADED_FOLDER + filename);
            List<String> result = read_csv.read();
            map.put("result", result);
        }

        return "review";
    }

}